<?php
/**
 * @Author: Shawn Zhang 
 * @Date: 2019-10-17 10:50:43 
 * @Last Modified by: Shawn Zhang
 * @Last Modified time: 2019-10-17 15:42:47
 */

namespace App\Services\Utils;

use App\Models\Admin;
use App\Models\Customer;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Tymon\JWTAuth\JWTAuth;
use Tymon\JWTAuth\JWTGuard;

class Guard
{
    /**
     * Delegate Gate Method On Auth::guard
     * @example
     *      Guard::matchId($admin_model, $operate_model)
     *
     * @param  string  $method
     * @param  mixed[2]  $parameters
     * @return mixed
     */
    public static function __callStatic($method, array $parameters)
    {
        list($admin, $arguments) = $parameters;

        return Gate::forUser($admin)->check($method, $arguments);
    }

    /**
     * @param $user
     *
     * @return string - token
     */
    public static function JWTAdminLogin(Admin $admin): string
    {
        return self::JWTLogin($admin, Admin::GUARD_NAME);
    }

    /**
     * @param $user
     *
     * @return string - token
     */
    public static function JWTCustomerLogin(Customer $customer): string
    {
        return self::JWTLogin($customer, Customer::GUARD_NAME);
    }

    /**
     * @param JWTSubject $user
     *
     * @param string $guard_name
     *
     * @return string - token
     */
    public static function JWTLogin(JWTSubject $user,
                                    string $guard_name): string
    {
        /** @var JWTAuth|JWTGuard $guard */
        $guard = Auth::guard($guard_name);

        $token = $guard->login($user);

        return $token;
    }

    public static function admin()
    {
        return Auth::guard(Admin::GUARD_NAME)->user();
    }

    public static function customer()
    {
        return Auth::guard(Customer::GUARD_NAME)->user();
    }
}